package ch3;

/**
 * final关键字的作用示例
 * final关键字保障修饰的字段被其他线程读取的时候读到的值是该字段初始值
 * 而非final字段则没有这种保障
 * 此外，对于引用类型final字段，final关键字还进一步确保该字段所引用的对象已经初始化完毕
 */

public class FinalFieldExample {
    final int x;
    int y;
    static FinalFieldExample instance;

    public FinalFieldExample() {
        x = 1;
        y = 2;
    }

    public static void writer() {
        instance = new FinalFieldExample();
    }

    public static void reader() {
        final FinalFieldExample theInstance = instance;
        if (theInstance != null) {
            int diff = theInstance.y - theInstance.x;
            System.out.println(diff);
        }
    }
}
